package cn.itzd.controller;

import cn.itzd.config.CaptchaProperties;
import cn.itzd.entity.SysUser;
import cn.itzd.entity.SysUserRole;
import cn.itzd.entity.dto.LoginUserDto;
import cn.itzd.enums.AppHttpCodeEnum;
import cn.itzd.handler.exception.SystemException;
import cn.itzd.service.LoginService;
import cn.itzd.utils.SecurityUtils;
import cn.itzd.utils.result.R;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.Map;

/**
 * @Author: dada
 * @Version: 1.0
 * @Description: 登录模块
 */
@RestController
public class LoginController extends BaseController {

    @Autowired
    private LoginService loginService;

    @Autowired
    private CaptchaProperties captchaProperties;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginUserDto loginUserDto) {
        if (StringUtils.isBlank(loginUserDto.getUserName())) {
            //提示 必须要传用户名
            throw new SystemException(AppHttpCodeEnum.REQUIRE_USERNAME);
        }
        return R.ok(loginService.login(loginUserDto));
    }


    @GetMapping("isLogin")
    public R<?> isLogin() {
        return R.ok(SecurityUtils.getUserId());
    }

    @PostMapping("reg")
    public R<?> reg(@RequestBody SysUser user) {
        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        user.setBirthday(new Date());
        userService.save(user);
        SysUserRole sysUserRole = new SysUserRole();
        sysUserRole.setUserId(user.getId());
        sysUserRole.setRoleId("2");
        userRoleService.save(sysUserRole);
        return R.ok();
    }
}
